/*
 * Copyright (c) 2009.
 */

package kz.home;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import java.io.InputStream;
import java.util.Hashtable;

/**
 * User: danik
 * Date: 01.04.2009
 * Time: 17:59:55
 */
public class MainFrame extends MIDlet implements CommandListener{
    protected Display display;
    protected Form fmMain;
    protected TextField textField;
    protected Command exitCommand;  // The exit command
    protected Command findCommand;  // The find command
    protected Hashtable table;
    protected StringItem question;
    protected StringItem answer;


    public MainFrame() {
        display = Display.getDisplay(this);
        fmMain = new Form("ПДД");

        init();
    }

    protected void init() {
        table = new Hashtable();

        question = new StringItem("Вопрос", " ");
        answer = new StringItem("Ответ", " ");

        textField = new TextField("Number", "", 4, TextField.NUMERIC);
        fmMain.append(textField);
        fmMain.append(question);
        fmMain.append(answer);

        exitCommand = new Command("Exit", Command.EXIT, 1);
        findCommand = new Command("Find", Command.OK, 1);

        fmMain.addCommand(exitCommand);
        fmMain.addCommand(findCommand);
        fmMain.setCommandListener(this);

        try {
            initPropertyFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void startApp() {
        display.setCurrent(fmMain);
    }

    protected void pauseApp() {}

    protected void destroyApp(boolean unconditional) {
        table = null;
        fmMain = null;
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }else if (command == findCommand) {
            findAnswer();
        }
    }

    protected void findAnswer() {
        String str = (String) table.get(textField.getString().trim());
        question.setText(textField.getString().trim());
        answer.setText("".equals(str) ? "" : str);
        textField.setString("");
    }

    private void initPropertyFile()throws Exception {
        InputStream is = getClass().getResourceAsStream("/list.txt");
        StringBuffer sb = new StringBuffer();
        try{
            int chars;
            while ((chars = is.read()) != -1) {
                if (chars == 10) {
                    initHashTable(sb.toString().trim());
                    sb = new StringBuffer();
                }
                sb.append((char) chars);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (is != null) is.close();
        }
    }

    private void initHashTable(String token) {
        int index = token.trim().indexOf("=");
        table.put(token.substring(0, index), token.substring(index + 1, token.length()));
    }
}
